import {createRouter, createWebHashHistory, useRouter} from "vue-router";
import routes, {homeRouterName, loginRouterName, routerPathMap} from "./routes.js";
import {useUserStore} from "@/store/sys/user.js";
import {profile} from "@/apis/sys/user.js";
import {useAuthStore} from "@/store/sys/auth.js";
import {tree2Routers} from "@/utils/index.js";
import {all} from "@/apis/sys/dict.js";
import {useDictStore} from "@/store/sys/dict.js";

const router = createRouter({
    history: createWebHashHistory(),
    routes: routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
    if (to.name !== loginRouterName) {
        const authStore = useAuthStore()
        const userStore = useUserStore()
        const dictStore = useDictStore()
        if (authStore.isLogin) {
            // 如果已经登录，则检查用户信息是否已经初始化
            if (!userStore.profileInitialized) {
                // 字典信息初始化
                const res = await all()
                if (res.code === 0) {
                    dictStore.initData(res.data)
                }
                // 用户信息初始化
                const {data} = await profile()
                await userStore.setUserInfo(data)
                // 动态添加路由
                const dynamicRoutes = tree2Routers(data.menuTree)
                for (const routerItem of dynamicRoutes) {
                    await router.addRoute(homeRouterName, {
                        ...routerItem,
                        component: routerPathMap[routerItem.component]
                    })
                }
                // 如果你决定在导航守卫内部添加或删除路由，通过返回新的位置来触发重定向
                next(to.fullPath)
                return
            }
        } else {
            next({name: loginRouterName, replace: true})
        }
    }
    next()
})

export default router